<style scoped lang="scss">
</style>
<template>
  <div class="app-container">
    <div class="">
      <el-form :inline="true" :model="listQuery">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="">
              <el-input v-model.trim="listQueryFieldValue" placeholder="请输入内容" class="input-with-select" clearable style="width: 380px;">
                <el-select slot="prepend" v-model="listQueryField" placeholder="请选择" style="width: 140px">
                  <el-option v-for="(item,key) in listQueryFieldMap" :key="key" :value="item.field" :label="item.label">{{ item.label }}</el-option>
                </el-select>
              </el-input>
            </el-form-item>
            <el-form-item label="">
              <el-select v-model="listQuery.category_id" placeholder="请选择任务分类" style="width: 180px;">
                <el-option v-for="(item,key) in categoryList" :key="key" :value="item.id" :label="item.name" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button v-waves plain class="filter-item" @click="resetGetList()">重置</el-button>
              <el-button v-waves type="primary" icon="el-icon-search" class="filter-item" @click="getList">搜索</el-button>
            </el-form-item>
          </el-col>
          <el-col :span="12" style="display: flex;flex-direction: row-reverse">
            <el-form-item>
              <el-button v-permission="['action:system:crontab:create']" v-waves type="primary" icon="el-icon-circle-plus-outline" class="filter-item" @click="clickCreate">新增任务</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <el-table
      v-loading="listLoading"
      :data="list"
      fit
      highlight-current-row
      border
      :header-cell-style="{background:'#eef1f6',color:'#606266'}"
    >
      <el-table-column align="center" type="index" width="70" label="序号" />
      <el-table-column label="任务分类名称" prop="category_info.name" />
      <el-table-column label="任务标题" prop="title" />
      <el-table-column label="任务名称" prop="name" />
      <el-table-column label="表达式" prop="pattern">
        <template v-slot="scope">
          {{ scope.row.pattern }}
        </template>
      </el-table-column>
      <el-table-column label="策略" prop="policy">
        <template v-slot="scope">
          {{ showLabel(policies, scope.row.policy) }}
        </template>
      </el-table-column>
      <el-table-column label="执行次数" prop="count" />
      <el-table-column label="排序" prop="sort" />
      <el-table-column label="状态" prop="status">
        <template v-slot="scope">
          <el-switch
            v-model="scope.row.status"
            class="custom-switch"
            inline-prompt
            disabled
            :active-value="1"
            :inactive-value="0"
          />
        </template>
      </el-table-column>
      <el-table-column label="备注" prop="remark" />
      <el-table-column label="创建时间" prop="created_at" width="160" />
      <el-table-column label="更新时间" prop="updated_at" width="160" />
      <el-table-column fixed="right" label="操作" width="300">
        <template v-slot="scope">
          <el-button v-permission="['action:system:crontab:update']" v-waves type="primary" size="mini" icon="el-icon-edit-outline" @click="clickUpdate(scope.row)">编辑</el-button>
          <el-button v-permission="['action:system:crontab:delete']" v-waves type="danger" size="mini" icon="el-icon-delete" @click="clickDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.page_size" @pagination="getList" />

    <!-- 新增|编辑弹窗 -->
    <el-dialog v-el-drag-dialog :close-on-click-modal="false" :title="formTitle" :visible.sync="formVisible" width="30%">
      <el-form ref="refForm" :model="form" :rules="rules" label-position="left" label-width="120px">
        <el-form-item label="请选择任务分类" prop="category_id">
          <el-select v-model="form.category_id" style="width: 100%;">
            <el-option v-for="(item,key) in categoryList" :key="key" :value="item.id" :label="item.name" />
          </el-select>
        </el-form-item>
        <el-form-item label="任务标题" prop="title">
          <el-input v-model.trim="form.title" clearable />
        </el-form-item>
        <el-form-item label="任务名称" prop="name">
          <el-input v-model.trim="form.name" clearable />
          <template>
            <div style="font-size: 0.8rem">
              任务名称请填写程序中注册的任务KEY
            </div>
          </template>
        </el-form-item>
        <el-form-item label="表达式" prop="pattern">
          <template slot="label">
            任务类型
            <el-tooltip class="item" effect="dark" placement="top">
              <i class="el-icon-question" />
              <div slot="content">
                <span>示例1：* * * * * * 【每秒执行】</span>
                <br>
                <span>示例2：2 * * * * * 【每分钟的第2秒执行】</span>
                <br>
                <span>示例3：# * * * * * 【每分钟执行，每一次执行至少间隔60秒】</span>
                <br>
                <span>示例4：# */30 * * * * 【每30分钟执行一次】</span>
              </div>
            </el-tooltip>
          </template>
          <el-input v-model="form.pattern" clearable />

          <template>
            <div style="font-size: 0.8rem">
              <el-link type="primary" target="_blank" href="https://goframe.org/pages/viewpage.action?pageId=30736411" :underline="false">表达式语法参考: https://goframe.org/pages/viewpage.action?pageId=30736411</el-link>
            </div>
          </template>
        </el-form-item>
        <el-form-item label="任务类型" prop="policy">
          <template slot="label">
            任务类型
            <el-tooltip class="item" effect="dark" placement="top">
              <i class="el-icon-question" />
              <div slot="content">
                1.普通定时任务：根据任务表达式配置情况执行<br>
                2.单例定时任务：即同时只能有一个该任务正在运行。当第二个相同的定时任务触发执行时，如果发现已有该任务正在执行，第二个任务将会退出不执行，定时器将会继续等待下一次定时任务的触发检测，以此类推<br>
                3.单次定时任务：添加只运行一次的定时任务，当运行一次数后该定时任务自动销毁<br>
                4.多次定时任务：添加运行指定次数的定时任务，当运行times次数后该定时任务自动销毁<br>
              </div>
            </el-tooltip>
          </template>
          <el-select v-model="form.policy" placeholder="请选择" style="width: 100%;" @change="clickChangePolicy">
            <el-option v-for="(item,key) in policies" :key="key" :value="item.value" :label="item.label" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="form.policy === 4" label="执行次数" prop="count">
          <el-input v-model.number="form.count" clearable />
        </el-form-item>
        <el-form-item label="执行参数" prop="params">
          <el-input v-model.trim="form.params" clearable />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择" style="width: 100%;">
            <el-option :value="1" label="启用" />
            <el-option :value="2" label="禁用" />
          </el-select>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model.number="form.sort" clearable />
        </el-form-item>
        <el-form-item label="备注" prop="remark" style="width: 100%;">
          <el-input
            v-model="form.remark"
            type="textarea"
            :autosize="{ minRows: 2, maxRows: 10}"
            placeholder="请输入内容"
            clearable
          />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button v-waves @click="formVisible = false">关闭</el-button>
        <el-button v-if="form.id === 0" v-permission="['action:system:crontab:create']" v-waves type="primary" @click="submitCreate()">确认新增</el-button>
        <el-button v-else v-permission="['action:system:crontab:update']" v-waves type="primary" @click="submitUpdate()">确认修改</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import Pagination from '@/components/Pagination/index.vue' // Secondary package based on el-pagination
import { createCrontab, deleteCrontab, getCrontabList, updateCrontab } from '@/api/system/crontab'
import { getCategoryList } from '@/api/system/crontab_category'
export default {
  name: 'SystemCrontabIndex',
  components: { Pagination },
  data() {
    return {
      list: null,
      total: 0,
      listLoading: false,
      listQueryFieldMap: [
        { field: 'title', label: '标题' },
        { field: 'name', label: '名称' }
      ],
      listQueryField: 'title',
      listQueryFieldValue: null,
      listQuery: {
        page: 1,
        page_size: 10,
        category_id: null,
        name: '',
        title: ''
      },
      formTitle: '新增',
      formVisible: false,
      form: {
        id: 0,
        category_id: null,
        title: '',
        name: '',
        pattern: '2 * * * * *',
        params: '',
        count: 0,
        policy: 1,
        sort: 0,
        status: 1,
        remark: ''
      },
      rules: {
        title: [
          { required: true, message: '请输入', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入', trigger: 'blur' }
        ],
        pattern: [
          { required: true, message: '请输入', trigger: 'blur' }
        ],
        policy: [
          { required: true, message: '请输入', trigger: 'blur' }
        ]
      },
      roleList: [],
      policies: [
        { value: 1, label: '普通定时任务' },
        { value: 2, label: '单例定时任务' },
        { value: 3, label: '单次定时任务' },
        { value: 4, label: '多次定时任务' }
      ],
      categoryList: []
    }
  },
  watch: {
    listQueryField(newField, oldField) {
      this.listQuery[newField] = this.listQueryFieldValue
      this.listQuery[oldField] = null
    },
    listQueryFieldValue(newValue, oldValue) {
      this.listQuery[this.listQueryField] = newValue
    }
  },
  created() {
    // 查询定时任务列表
    this.getList()

    // 查询分类
    this.getCategoryList()
  },
  methods: {
    resetGetList() {
      this.listQuery = {
        page: 1,
        page_size: 10,
        keyword: ''
      }
      this.listQueryFieldValue = null
      this.getList()
    },
    getList() {
      this.listLoading = true
      getCrontabList(this.listQuery).then(res => {
        this.list = res.list
        this.total = res.total
      })
      this.listLoading = false
    },
    getCategoryList() {
      getCategoryList({
        page: 1,
        page_size: 1000
      }).then(res => {
        this.categoryList = res.list || []
      })
    },
    resetFormData() {
      this.form = {
        id: 0,
        category_id: null,
        title: '',
        name: '',
        pattern: '2 * * * * *',
        params: '',
        count: 0,
        policy: 1,
        sort: 0,
        status: 1,
        remark: ''
      }
    },
    clickCreate() {
      this.resetFormData()
      this.getCategoryList()
      this.formTitle = '新增'
      this.formVisible = true
    },
    submitCreate() {
      this.$refs['refForm'].validate((valid) => {
        if (valid) {
          createCrontab(this.form).then(res => {
            this.getList()
            this.$message({
              message: '创建成功',
              type: 'success'
            })
            this.formVisible = false
          }).then(res => {})
        }
      })
    },
    clickUpdate(item) {
      this.form = {
        id: item.id,
        category_id: item.category_id,
        title: item.title,
        name: item.name,
        pattern: item.pattern,
        params: item.params,
        count: item.count,
        policy: item.policy,
        sort: item.sort,
        status: item.status,
        remark: item.remark
      }
      this.formTitle = '编辑'
      this.formVisible = true
    },
    submitUpdate() {
      this.$refs['refForm'].validate((valid) => {
        if (valid) {
          updateCrontab(this.form).then(res => {
            this.getList()
            this.$message({
              message: '编辑成功',
              type: 'success'
            })
            this.formVisible = false
          }).then(res => {})
        }
      })
    },
    clickDelete(item) {
      this.$confirm(`此操作将永久删除该配置[${item.name}], 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.submitDelete(item.id)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    submitDelete(id) {
      deleteCrontab({ id: id }).then(res => {
        this.getList()
        this.$message({
          message: '删除成功',
          type: 'success'
        })
        this.formVisible = false
      }).then(res => {})
    },
    clickChangePolicy(val) {
      this.form.count = 0
    },
    showLabel(items, value) {
      for (const item of items) {
        if (item.value === value) {
          return item.label
        }
      }
      return ''
    }
  }
}
</script>
